package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.config.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * app端登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1 参数校验
        if (dto == null || dto.getEquipmentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 判断用户是否使用手机号登录
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {  // 手机号登录
            // 根据手机号查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone,dto.getPhone()).eq(ApUser::getStatus,0 ));
            if (apUser == null) {
                CustException.cust("用户不存在或被锁定");
            }

            // 比对密码
            String salt = apUser.getSalt();
            String dbpassword = apUser.getPassword();
            String newPad = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
            if (!newPad.equals(dbpassword)) {
                CustException.cust("用户名或密码错误");
            }

            //4 生成令牌jwt，返回用户信息
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            apUser.setPassword(null);
            apUser.setSalt(null);

            Map map = new HashMap();
            map.put("token", token);
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        } else {
            //3 默认登录
            Map map = new HashMap();
            String token = AppJwtUtil.getToken(0L);
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
    }
}
